package com.example.ui.register;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import com.example.huashangapp.R;
import com.example.net.NetRequest;
import com.example.util.Util;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class Register1Fm extends Fragment {
	public static ImageView ra_register1;
	public static String photoPath;
	LinearLayout ra_l1_bottom;
	ImageView commentphoto;
	private Button ra1_return, ra1_next, ra_l1_exit, ra_l1_photos,
			ra_l1_carmera;
	private TextView ra1_title;
	public static boolean canNext = false;

	
	
	
	Bitmap photo;
	public static String imagenames, Filename;
	public static Handler handler;
	View v;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		 v = inflater.inflate(R.layout.a_register1, null);
		init(v);

		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 0:
                   canNext=true;
                   next();
					break;
				case 1:
					Util.toast(getActivity(), "图片上传失败");
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}
		};
		return v;
	}
	private void next(){
		if(canNext==true){
			Register2Fm register2=new Register2Fm();
			FragmentManager fm = getFragmentManager();
			FragmentTransaction ft = fm.beginTransaction();
			ft.replace(R.id.l,register2);
			ft.addToBackStack(null);
			ft.commit();			
           }
	}

	private void init(View v) {
		
		ra1_return = (Button) v.findViewById(R.id.register_return);
		ra1_next = (Button) v.findViewById(R.id.register_next);
		ra1_title = (TextView) v.findViewById(R.id.register_title);
		ra_register1 = (ImageView) v.findViewById(R.id.ar_register1);
		ra_l1_photos = (Button) v.findViewById(R.id.ar_l1_photos);
		ra_l1_carmera = (Button) v.findViewById(R.id.ar_l1_carmera);
		ra_l1_exit = (Button) v.findViewById(R.id.ar_l1_exit);
		ra_l1_bottom = (LinearLayout) v.findViewById(R.id.ar_l1_bottom);
		ra1_title.setText("添加名片(1/5)");
		ra1_return.setOnClickListener(ra_ocl);
		ra1_next.setOnClickListener(ra_ocl);
		ra_register1.setOnClickListener(ra_ocl);
		ra_l1_photos.setOnClickListener(ra_ocl);
		ra_l1_carmera.setOnClickListener(ra_ocl);
		ra_l1_exit.setOnClickListener(ra_ocl);

	}

	OnClickListener ra_ocl = new OnClickListener() {

		@Override
		public void onClick(View v) {
			
			switch (v.getId()) {
			case R.id.ar_register1:
				if(ra_l1_bottom.getVisibility()==View.VISIBLE){
					ra_l1_bottom.setVisibility(View.GONE);
				}else{
					ra_l1_bottom.setVisibility(View.VISIBLE);
				}
				
				break;
			case R.id.ar_l1_photos:// 相册
				getPicFromContent();
				break;
			case R.id.ar_l1_carmera:// 拍照
				getPicFromCapture();
				break;
			case R.id.ar_l1_exit:// 取消
				ra_l1_bottom.setVisibility(View.GONE);
				break;
			case R.id.register_next:// 上传图片
				if(canNext==true){
					next();
				}else{
				NetRequest.uploadPic(getActivity(), Filename);
				}
				break;
			case R.id.register_return:
				getActivity().finish();
				break;

			default:
				break;
			}
		}
	};

	// 拍照
	private void getPicFromCapture() {
		try {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			// 获得名字
			imagenames = UUID.randomUUID() + ".jpg";
			Filename = Environment.getExternalStorageDirectory() + "/"
					+ imagenames;
			// 下面这句指定调用相机拍照后的照片存储的路径
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Filename)));
			startActivityForResult(intent, 1);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	// 相册
	private void getPicFromContent() {
		try {
			Intent album = new Intent(Intent.ACTION_GET_CONTENT);
			album.setType("image/*");
			startActivityForResult(album, 2);
		} catch (ActivityNotFoundException e) {
		}
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == 1) {

			startPhotoZoom(Uri.fromFile(new File(Filename)));

		} else if (requestCode == 2) {

			if (data != null) {

				Uri uri = data.getData();// 可以得到图片在Content：//。。。中的地址，把它转化成绝对地址如下
				String[] proj = { MediaStore.Images.Media.DATA };
				// 参数：proj 是指查哪一列
				Cursor cursor = getActivity().managedQuery(uri, proj, null, null, null);
				if (cursor != null) {
					int column_index = cursor
							.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
					if (cursor.getCount() > 0 && cursor.moveToFirst()) {
						Filename = cursor.getString(column_index);
						String name = Filename.substring(Filename
								.lastIndexOf("/"));
						imagenames = System.currentTimeMillis()
								+ name.substring(name.indexOf("."));
						startPhotoZoom(data.getData());
					}

				}

			}

		} else if (requestCode == 3) {
			/**
			 * 非空判断大家一定要验证，如果不验证的话， 在剪裁之后如果发现不满意，要重新裁剪，丢弃
			 * 当前功能时，会报NullException，可以根据不同情况在合适的 地方做判断处理类似情况
			 * 
			 */
			if (data != null) {
				try {
					setPicToView(data);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else {
			getActivity().finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 剪裁图片的方法
	 * 
	 * @param uri
	 */
	private void startPhotoZoom(Uri uri) {  
	
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 5);
		intent.putExtra("aspectY", 3);
		// outputX outputY 是裁剪图片宽高
		intent.putExtra("outputX", 400);
		intent.putExtra("outputY", 240);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	/**
	 * 保存剪裁之后的图片
	 * 
	 * @param picdata
	 * @throws IOException
	 */
	private void setPicToView(Intent picdata) throws IOException {
		Bundle extras = picdata.getExtras();
		if (extras != null) {
			photo = extras.getParcelable("data");
			// 压缩
			photo = imageZoom(photo);
			File f1 = new File(getActivity().getCacheDir(), imagenames);
			Filename = getActivity().getCacheDir() + "/" + imagenames;
			savePic(photo, f1.getPath());

			ra_register1.setImageBitmap(photo);
			ra_l1_bottom.setVisibility(View.GONE);
		}

	}

	public Bitmap imageZoom(Bitmap bitMap) {
		// 图片允许最大空间 ：单位：KB
		double maxSize = 200.00;
		// 将bitmap放至数组中，意在bitmap的大小（与实际读取的原文件要大）
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bitMap.compress(Bitmap.CompressFormat.JPEG, 70, baos);// 70 -- 压缩率 ；
																// 100是不压缩、压缩率为0；
		byte[] b = baos.toByteArray();

		// 将字节换成KB
		double mid = b.length / 1024;
		// 判断bitmap占用空间是否大于允许最大空间 如果大于则压缩 小于则不压缩
		if (mid > maxSize) {
			// 获取bitmap大小 是允许最大大小的多少倍
			double i = mid / maxSize;
			// 开始压缩 此处用到平方根 将宽带和高度压缩掉对应的平方根倍
			// （1.保持刻度和高度和原bitmap比率一致，压缩后也达到了最大大小占用空间的大小）
			bitMap = zoomImage(bitMap, bitMap.getWidth() / Math.sqrt(i),
					bitMap.getHeight() / Math.sqrt(i));
			return bitMap;
		}

		return bitMap;
	}

	public static void savePic(Bitmap b, String strFileName) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(strFileName);
			if (null != fos) {
				b.compress(Bitmap.CompressFormat.PNG, 70, fos);
				fos.flush();
				fos.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/***
	 * 图片的缩放方法
	 * 
	 * @param bgimage
	 *            ：源图片资源
	 * @param newWidth
	 *            ：缩放后宽度
	 * @param newHeight
	 *            ：缩放后高度
	 * @return
	 */
	public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
			double newHeight) {
		// 获取这个图片的宽和高
		float width = bgimage.getWidth();
		float height = bgimage.getHeight();
		// 创建操作图片用的matrix对象
		Matrix matrix = new Matrix();
		// 计算宽高缩放率
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// 缩放图片动作
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
				(int) height, matrix, true);
		return bitmap;
	}

}
